<template>
  <div class="consult-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
      <el-row :gutter="20" class="user-cards">
        <el-col
          v-for="user in users"
          :key="user.id"
          :xs="24"
          :sm="24"
          :md="24"
        >
          <el-card
            class="user-card"
            :class="{ 'active-user': activeUser === user.id }"
            shadow="hover"
            @click="handleUserSelect(user.id)"
          >
            <div class="card-content">
              <div class="user-avatar">
                <el-avatar :size="56" :src="user.avatar" />
              </div>
              <div class="user-info">
                <div class="user-header">
                  <h4 class="user-name">{{ user.userRealName }}</h4>
                  <span class="last-time">{{ formatTime(user.createTime) }}</span>
                </div>
                <div class="user-gender">
                  <el-icon v-if="user.gender === 1" color="#409EFF"><Male /></el-icon>
                  <el-icon v-else color="#F56C6C"><Female /></el-icon>
                </div>
                <div class="last-message">{{ user.lastMessage }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div v-if="activeUser" class="chat-header">
        <el-avatar :size="40" :src="getSelectedUser?.avatar" />
        <span class="chat-title">{{ getSelectedUser?.userRealName }}</span>
      </div>
      <el-scrollbar class="message-area" style="overflow-x: hidden;">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message-bubble"
          :class="{ 'user-message': msg.senderId === getUser().userInfo.id }"
        >
          <div class="message-content">
            <p class="message-text">{{ msg.content }}</p>
            <span class="message-time">{{ formatTime(msg.createTime) }}</span>
          </div>
        </div>
      </el-scrollbar>

      <div class="input-area">
        <el-input
          v-model="newMessage"
          placeholder="输入消息内容"
          type="textarea"
          :rows="3"
          resize="none"
        />
        <div class="send-button">
          <el-button type="primary" @click="sendMessageHandler">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import { faker } from '@faker-js/faker/locale/zh_CN'
import dayjs from 'dayjs'
import { getUser } from '@/store/userStore.js'
import { Male, Female } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/time'
import {getUserListPage} from "@/api/user.js";
import {getConsultList, sendMessage} from "@/api/consult.js";

// 生成模拟用户列表
const users = ref([]);

// 当前选中的用户
const activeUser = ref(null)
const newMessage = ref('')



// 当前显示的消息列表
const messages = ref([])

// 获取选中的用户信息
const getSelectedUser = computed(() => {
  return users.value.find(user => user.id === activeUser.value)
})

// 处理用户选择
const handleUserSelect = async (userId) => {
  activeUser.value = userId
  messages.value = []
  const res = await getConsultList({
    senderId: getUser().userInfo.id,
    receiverId: userId
  })
  messages.value = res.data.reverse()
}

// 发送消息处理
const sendMessageHandler = async () => {
  if (!newMessage.value.trim() || !activeUser.value) return

  const newMsg = {
    senderId: getUser().userInfo.id,
    receiverId: activeUser.value,
    content: newMessage.value,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  }

  // 清空输入框
  newMessage.value = ''

  // 发送消息
  await sendMessage(newMsg)
  await handleUserSelect(activeUser.value)
}

// 获取所有用户
const getAllUsers = async () => {
  const res = await getUserListPage({
    page: 1,
    size: 10000,
    type: 2
  })
  if (res.code === 200) {
    users.value = res.data.records
  }

  // 过滤掉messages为[]的用户
  const filteredUsers = users.value.map(async user => {
    const res = await getConsultList({
      senderId: getUser().userInfo.id,
      receiverId: user.id
    })
    return res.data.length > 0 ? user : null;
  })
  users.value = (await Promise.all(filteredUsers)).filter(user => user !== null)
}

onMounted(() => {
  getAllUsers()
})
</script>

<style scoped lang="scss">
.consult-container {
  display: flex;
  height: 80vh;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .user-list {
    width: 280px;
    max-height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    border-right: 1px solid #ebeef5;
    padding: 16px;

    .user-card {
      margin-bottom: 12px;
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      &.active-user {
        border: 2px solid var(--el-color-primary);
        background-color: rgba(64, 158, 255, 0.08);
      }

      .card-content {
        display: flex;
        align-items: center;
        gap: 12px;
      }

      .user-info {
        flex: 1;
        overflow: hidden;

        .user-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 4px;

          .user-name {
            margin: 0;
            font-size: 16px;
            color: #303133;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .last-time {
            font-size: 12px;
            color: #909399;
          }
        }

        .user-gender {
          display: flex;
          align-items: center;
          margin-bottom: 4px;
        }

        .last-message {
          font-size: 14px;
          color: #606266;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chat-header {
      padding: 16px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      align-items: center;
      gap: 12px;
      background: #fff;

      .chat-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .message-area {
      flex: 1;
      padding: 20px;
      background: #f8f9fa;
      overflow-y: auto;

      .message-bubble {
        margin-bottom: 16px;
        display: flex;
        flex-direction: column;

        &.user-message {
          align-items: flex-end;

          .message-content {
            background: var(--el-color-primary);
            color: #fff;
            border-radius: 12px 12px 0 12px;

            .message-time {
              color: rgba(255, 255, 255, 0.8);
            }
          }
        }

        .message-content {
          max-width: 70%;
          padding: 12px 16px;
          background: #fff;
          border-radius: 12px 12px 12px 0;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

          .message-text {
            margin: 0;
            font-size: 14px;
            line-height: 1.5;
            color: #303133;
          }

          .message-time {
            display: block;
            margin-top: 4px;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .input-area {
      padding: 16px;
      border-top: 1px solid #ebeef5;
      background: #fff;

      .send-button {
        margin-top: 12px;
        text-align: right;
      }
    }
  }
}
</style>
